package com.itcast.tanhuaserver.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itcast.tanhuaserver.utils.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.concurrent.TimeUnit;

/**
 * @PachageName: com.itcast.tanhuaserver.interceptor
 * @ClassName:
 * @Description: TODO
 * @Author: Hushi
 * @DateTime: 2021/2/1615:10
 * @Version 1.0
 */
@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice {

    @Value("${tanhua.cache.enable}")
    private Boolean enable;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //以下条件 : // 开关处于开启状态  是get请求  包含了@Cache注解
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return enable && methodParameter.hasMethodAnnotation(GetMapping.class) && methodParameter.hasMethodAnnotation(Cache.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest request, ServerHttpResponse serverHttpResponse) {
        if (null == body){
            return null;
        }
        try {
            String redisValue = null;
            if (body instanceof String){
                redisValue = (String)body;
            }
            else{
                redisValue = MAPPER.writeValueAsString(body);
            }
            String rediskey = RedisCacheInterceptor.createRedisKey(((ServletServerHttpRequest)request).getServletRequest());
            Cache cache = methodParameter.getMethodAnnotation(Cache.class);
            this.redisTemplate.opsForValue().set(rediskey,redisValue,Long.parseLong(cache.time()), TimeUnit.SECONDS);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return body;
    }
}
